package com.ppyydd.sms.servlets;

import com.ppyydd.sms.beans.Student;
import com.ppyydd.sms.service.IStudentService;
import com.ppyydd.sms.service.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String num = request.getParameter("num");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String ageStr = request.getParameter("age");
        String scoreStr = request.getParameter("score");
        HttpSession session = request.getSession();
        if (num == null || "".equals(num)) {
            session.setAttribute("message", "学号不能为空");
            response.sendRedirect(request.getContextPath() + "/register.jsp");
            return;
        }
        if (name == null || "".equals(name)) {
            session.setAttribute("message", "姓名不能为空");
            response.sendRedirect(request.getContextPath() + "/register.jsp");
            return;
        }
        if (ageStr == null || "".equals(ageStr)) {
            session.setAttribute("message", "年龄不能为空");
            response.sendRedirect(request.getContextPath() + "/register.jsp");
            return;
        }
        if (scoreStr == null || "".equals(scoreStr)) {
            session.setAttribute("message", "成绩不能为空");
            response.sendRedirect(request.getContextPath() + "/register.jsp");
            return;
        }
        if (password == null || "".equals(password)) {
            session.setAttribute("message", "密码不能为空");
            response.sendRedirect(request.getContextPath() + "/register.jsp");
            return;
        }
        int age = Integer.parseInt(ageStr);
        double score = Double.parseDouble(scoreStr);
        Student student = new Student(name, age, score, num, password);
        IStudentService service = new StudentServiceImpl();
        Integer id = service.setStudent(student);
        System.out.println(id);

        if (id == null) {
            response.sendRedirect(request.getContextPath() + "/register.jsp");
            return;
        }
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
